/**
 * Created by xiewei on 4/26/17.
 *  m 专场ID
 *  value 搜索内容
 */

var mId = getURLParameter('m'), name = getURLParameter('name');
//搜索条件
var searchParam = {
    cPage: 1,
    pSize: 20,
    marketId: mId,
    userId: USER.userId,
    brandId: '',
    type: '',
    action: '',
    start: '',
    end: ''
};
/**
 * 筛选面板
 */
var FilterBar = React.createClass({
    handleFilterPanelClick: function(e){
        this.props.toggleFilter();
        e.stopPropagation();
        e.preventDefault();
    },
    handleSalesSearchClick: function(e){
        var $that= $(e.target);
        if($that.hasClass('am-icon-long-arrow-down')){
            $that.removeClass("am-icon-long-arrow-down").addClass("am-icon-long-arrow-up");
            searchParam.action = 3;
        }else {
            $that.removeClass("am-icon-long-arrow-up").addClass("am-icon-long-arrow-down");
            searchParam.action = 4;
        }
        this.props.refreshList();
        this.props.search(true);
        e.stopPropagation();
        e.preventDefault();
    },
    handlePriceSearchClick: function(e){
        var $that= $(e.target);
        if($that.hasClass('am-icon-long-arrow-down')){
            $that.removeClass("am-icon-long-arrow-down").addClass("am-icon-long-arrow-up");
            searchParam.action = 1;
        }else {
            $that.removeClass("am-icon-long-arrow-up").addClass("am-icon-long-arrow-down");
            searchParam.action = 2;
        }
        this.props.refreshList();
        this.props.search(true);
        e.stopPropagation();
        e.preventDefault();
    },
    render: function(){
        return(
            <div className="am-g am-g-collapse expert_tabs bg-white am-text-center border-bottom padding-top-bottom-10 font-15 font-color-2 tab-fixed filter_menu">
                <div className="am-u-sm-4 "><a id="secure_fenlei" className="prelative" onClick={this.handleSalesSearchClick}>销量<span className="am-icon-long-arrow-down am-margin-left-xs sort font-12"></span></a></div>
                <div className="am-u-sm-4 "><a id="secure_paixu" className="prelative" onClick={this.handlePriceSearchClick}>价格<span className="am-icon-long-arrow-down am-margin-left-xs sort font-12"></span></a></div>
                <div className="am-u-sm-4 "><a className="prelative" onClick={this.handleFilterPanelClick}>筛选<span className="am-icon-angle-down margin-left-5"></span></a></div>
            </div>
        )
    }
});
//搜索分类项目名
//<div className="font-color-1 font-14 am-padding-right-sm">更多<span className="am-icon-angle-down margin-left-5"></span></div>
var FilterPanelLabel = React.createClass({
    render: function(){
        return (
            <div className="bg-white border-bottom" >
                <div data-am-widget="titlebar" className="am-titlebar am-titlebar-default box prelative  am-no-layout">
                    <i className="bgmainblock"></i>
                    <h2 className="am-titlebar-title box-1">{this.props.title}</h2>
                </div>
            </div>
        )
    }
});
//搜索分类项目内容
var FilterPanelList = React.createClass({
    handleFilterClick: function(e) {
        var target = e.target;
        if(target.nodeName === 'A'){
            var $p = $(e.target).parent();
            $p.siblings("li").removeClass("am-active");
            $p.addClass("am-active");
        }
    },
    render: function(){
        var arr = [], list = this.props.types ? this.props.types : this.props.brands;
        list.forEach((value) => {
            arr.push(<li data-id={value.id}><a>{value.name}</a></li>);  //选中class am-active
        });
        return <div className="bg-white am-padding-top-xs" >
            <div className="am-padding-left-sm" >
                <ul id={this.props.id} onClick={this.handleFilterClick} className="tag am-pagination am-pagination-default hotsearch">
                    {arr}
                </ul>
            </div>
        </div>
    }
});
//筛选面板
var FilterPanel = React.createClass({
    getInitialState: function() {
        return {
            types: [],
            brands: [],
            prices: []
        }
    },
    showMsg: function(msg) {
        this.setState({
            msgHidden: false,
            msg: msg
        });
        return false;
    },
    componentWillMount: function() {
        $.ajax(
            getAjaxOps('/offer/initSerchCond')
        ).done(function (res){
                if(res.resultCode == 0){
                    var arr = res.data.price.split(','),l = arr.length, prices = [],types = [],brands = [];
                    for(var i = 0; i < l ; i++){
                        if(i === l-1){
                            prices.push([arr[i]]);
                        }else{
                            prices.push([arr[i], arr[i+1]]);
                        }
                    }
                    res.data.types.forEach(function(value){
                        types.push({
                            id: value.id,
                            name: value.offer_type_name
                        })
                    });
                    res.data.brands.forEach(function(value){
                        brands.push({
                            id: value.id,
                            name: value.brand_name
                        })
                    });
                    this.setState({
                        types: types,
                        brands: brands,
                        prices: prices
                    })
                }
            }.bind(this));
    },
    handlePriceClick: function(e) {
        var target = e.target;
        if(target.nodeName === 'A'){
            var $p = $(target).parent();
            $p.siblings("li").removeClass("am-active");
            $p.addClass("am-active");
            //最高|最低价格填入input框
            var low = target.getAttribute('data-low'),
                high = target.getAttribute('data-high'),
                lowInput = ReactDOM.findDOMNode(this.refs.low),
                highInput = ReactDOM.findDOMNode(this.refs.high);
            lowInput.value = low;
            if(high){
                highInput.value = high;
            }else{
                highInput.value = '';
            }
            //e.stopPropagation();
            //e.preventDefault();
        }
    },
    handleClearCondClick: function(e) {
        //清空筛选条件
        //var actives = document.querySelectorAll('.am-active');
        //actives.forEach(function (el) {
        //    el.className = el.className.replace(/am-active/g,'');
        //});
        $('.am-active').removeClass('am-active');
        ReactDOM.findDOMNode(this.refs.low).value = '';
        ReactDOM.findDOMNode(this.refs.high).value = '';
        e.stopPropagation();
        e.preventDefault();
    },
    handleFilterSearchClick: function(e) {
        //根据筛选条件搜索
        var $brandLi = $('#brands').find('li.am-active'),
            $typeLi = $('#types').find('li.am-active');
        if($brandLi){
            searchParam.brandId = $brandLi.attr('data-id');
        }
        if($typeLi){
            searchParam.type = $typeLi.attr('data-id');
        }
        searchParam.start = ReactDOM.findDOMNode(this.refs.low).value.replace(/以上/g, '');
        searchParam.end = ReactDOM.findDOMNode(this.refs.high).value;
        if(searchParam.start >= searchParam.end){
            return this.showMsg("价格区间有误");
        };
        //隐藏面板
        this.props.toggleFilter();
        this.props.refreshList();
        this.props.search(true);
        e.stopPropagation();
        e.preventDefault();
    },
    render: function() {
        var searchPriceArr = [], styleObj = {};
        this.state.prices.forEach((value) => {
            if(value[1]){
                searchPriceArr.push(
                    <li><a data-low={value[0]} data-high={value[1]}>{value[0]+'-'+value[1]}</a></li>
                )
            }else{
                searchPriceArr.push(
                    <li><a data-low={value[0]} data-high=''>{value[0]+'以上'}</a></li>
                )
            }
        });
        if(this.props.isFilter){
            styleObj = {'display': 'block'}
        }else {
            styleObj = {'display': 'none'}
        }
        return(
            <div className="filter-container" style={styleObj}>
                <FilterPanelLabel title={'分类'} /><FilterPanelList id={'types'} types={this.state.types} />
                <FilterPanelLabel title={'分类'} /><FilterPanelList id={'brands'} brands={this.state.brands} />
                <FilterPanelLabel title={'价格'} />
                <div className="bg-white am-padding-top-xs">
                    <div className="am-padding-left-sm ">
                        <ul className="tag am-pagination am-pagination-default hotsearch" onClick={this.handlePriceClick}>
                            {searchPriceArr}
                        </ul>
                    </div>
                </div>
                <div className="box bg-white am-padding-bottom-sm am-padding-left-lg am-padding-right-lg am-padding-top-sm">
                    <div><input type="tel" className="input-7" placeholder="最低价" ref="low"/></div>
                    <div className="box-1 font-color-1 am-text-center">--</div>
                    <div><input type="tel" className="input-7" placeholder="最高价" ref="high"/></div>
                </div>
                <div className="am-g bg-white am-padding-top-sm am-padding-bottom-sm">
                    <div className="am-u-sm-6">
                        <div className="order-btn-3 am-text-center" onClick={this.handleClearCondClick}>清空条件</div>
                    </div>
                    <div className="am-u-sm-6">
                        <div id="btnenter" className="order-btn-2 am-text-center" onClick={this.handleFilterSearchClick}>确定</div>
                    </div>
                </div>
            </div>
        )
    }
});
/**
 * 商品列表
 * 搜索|筛选结果
 */
var GoodsItem = React.createClass({
    handleSearchRecentClick: function(){
        location.href='detail.html?goodId='+this.props.data.id;
    },
    render: function() {
        //var price ;
        //switch (''+this.props.data.flag){
        //    case '0': price = this.props.data.in_price.toPrice();break;
        //    case '2': price = this.props.data.out_price.toPrice();break;
        //    default: price = '-';break;
        //}
        return (
            <div className="box-1 am-margin-right-sm prelative">
                <div onClick={this.handleSearchRecentClick} className="goodpic">
                    <img className="width-100" src={IMG_PRE+this.props.data.url} /><i className="icon-cuxiao"></i>
                </div>
                <div className="am-margin-top-xs font-color-11 am-text-truncate">{this.props.data.offer_name}</div>
                <div className="am-g am-g-collapse am-margin-top-xs">
                    <div className="am-u-sm-12 ">
                        <div className="box">
                            <div className="box-1 font-color-monney">
                                <div className="line20px"><span>&yen;</span><span className="font-18 margin-left-2">{this.props.data.out_price}</span></div>
                                <div className=""><span className="font-color-1 font-12">已售{this.props.data.cnt}</span></div>
                            </div>
                            <div className="am-margin-right-xs">
                                <div className={'my-icon-guanzhu' + (this.props.data.keep != 0 ? ' cur' : '')} data-id={this.props.data.id}></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
});
//搜索结果列表
var GoodsList = React.createClass({
    handleHeartClick: function(e) {
        var target = e.target, cName = target.className;
        if(target !== e.currentTarget && cName.indexOf('my-icon-guanzhu') >= 0 && ifUser()){
            var param = {
                userId: USER.userId,
                offerId: target.getAttribute('data-id')
            };
            if(cName.indexOf('cur') >= 0){
                $.ajax(
                    getAjaxOps('/offer/removeKeep', param)
                ).done(function(res) {
                        if(res.resultCode == 0){
                            target.className = cName.replace(/cur/g, '');
                        }
                    });
            }else{
                $.ajax(
                    getAjaxOps('/offer/addKeep', param)
                ).done(function(res) {
                        if(res.resultCode == 0){
                            target.className = cName + ' cur';
                        }
                    });
            }
        }
    },
    render: function() {
        var goodsItemsArr = [], l = this.props.goodsList.length;
        for(var i = 0; i < l; i += 2){
            if(i === l-1){
                goodsItemsArr.push(
                    <div className="item am-margin-bottom-sm">
                        <div className="box">
                            <GoodsItem data={this.props.goodsList[i]}/>
                        </div>
                    </div>
                );
            }else{
                goodsItemsArr.push(
                    <div className="item am-margin-bottom-sm">
                        <div className="box">
                            <GoodsItem data={this.props.goodsList[i]}/>
                            <GoodsItem data={this.props.goodsList[i+1]} />
                        </div>
                    </div>
                );
            }
        }
        if(this.props.isLast){
            //最后一页
            goodsItemsArr.push(
                <div className="item am-margin-bottom-sm">
                    <div className="box">
                        <div className="goods-no-more"><p>没有更多数据了~</p></div>
                    </div>
                </div>
            )
        }
        return(
            <div onClick={this.handleHeartClick} className="list margin-top-42 am-padding-top-sm bg-white am-padding-left-sm ">
                {goodsItemsArr}
            </div>
        )
    }
});
var SearchResultPage = React.createClass({
    render: function() {
        var styleObj = {};
        if(this.props.isFilter){
            styleObj = {'display': 'block'}
        }else {
            styleObj = {'display': 'none'}
        }
        return (
            <section data-tag="css-nav">
                <FilterBar search={this.props.search} toggleFilter={this.props.toggleFilter} refreshList={this.props.refreshList}/>
                <FilterPanel isFilter={this.props.isFilter} search={this.props.search} toggleFilter={this.props.toggleFilter} refreshList={this.props.refreshList}/>
                <div className="global-mask" style={styleObj}></div>
                <GoodsList isLast={this.props.isLast} goodsList={this.props.goodsList}/>
            </section>
        )
    }
});
var dataList = [];
var Page = React.createClass({
    getInitialState: function() {
        return{
            isLast: false, //商品是否搜索至最后一页
            isFilter: false, //筛选面板是否展示
            isLoading: false, //是否正在加载
            goodsList: []   //结果商品列表
        }
    },
    componentWillMount: function(){
        this.search();
    },
    componentDidMount: function() {
        window.onscroll = this.load;
    },
    load: function() {
        if(!this.state.isLoading && (getClientHeight() + getDocumentTop() >= getScrollHeight())){
            this.search();
        }
    },
    search: function(flag) {
        if(!flag && this.state.isLast){
            return false;
        }
        this.setState({
            isLoading: true
        });
        $.ajax(
            getAjaxOps('/market/qryOffersByMarket', searchParam)
        ).done(function (res) {
                if(res.resultCode == 0){
                    this.setState({
                        isLoading: false
                    });
                    if(flag){
                        dataList = res.data.list;
                    }else {
                        Array.prototype.push.apply(dataList,res.data.list);
                    }
                    this.setState({
                        goodsList: dataList
                    });
                    if(!res.data.lastPage){
                        searchParam.cPage++;
                    }else{
                        //最后一页
                        this.setState({
                            isLast: true
                        })
                    }
                }
            }.bind(this));
    },
    toggleFilter: function() {
        this.setState({
            isFilter: !this.state.isFilter
        })
    },
    refreshList: function(){
        this.setState({
            isLast: false
        })
    },
    render: function() {
        return (
            <div>
                <Header title={name} cart={true}/>
                <SearchResultPage search={this.search} isLast={this.state.isLast} goodsList={this.state.goodsList}
                                  isFilter={this.state.isFilter} toggleFilter={this.toggleFilter} refreshList={this.refreshList}/>
            </div>
        )
    }
});

ReactDOM.render(
    <Page />,
    document.getElementById('root')
);
